package com.doform.android.xianggucheng.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.doform.android.xianggucheng.IApplication;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.bean.URLBean;
import com.doform.android.xianggucheng.bean.VersionUpdate;
import com.doform.android.xianggucheng.bean.request_bean.ReqVersion;
import com.doform.android.xianggucheng.fragment.BaseFragment;
import com.doform.android.xianggucheng.fragment.HomeFragment;
import com.doform.android.xianggucheng.fragment.MoneyFragment;
import com.doform.android.xianggucheng.help.AppHelp;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.service.DownloadService;
import com.doform.android.xianggucheng.service.PushService;
import com.doform.android.xianggucheng.utils.AppUtils;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.utils.http.HttpUtils;
import com.igexin.sdk.PushManager;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.f_ms.runtimepermission.simple.PermissionRefuseResultHelper;
import cn.f_ms.runtimepermission.simple.ShowRequestPermissionRationaleListener;
import cn.f_ms.runtimepermission.simple.SimpleRuntimePermission;
import io.reactivex.annotations.NonNull;
import okhttp3.Call;

import static com.doform.android.xianggucheng.utils.TsUtils.showToast;

/**
 * Created by Administrator on 2017/5/9.
 */

public class MainActivity extends BaseActivity {

    @BindView(R.id.btn_home)
    Button mHome;

    @BindView(R.id.btn_money)
    Button mMoney;

    private HomeFragment mHomeFragment;
    private MoneyFragment mMoneyFragment;
    private BaseFragment[] mFragments;
    private String updateMessage;
    private String apkUrl;

    @Override
    protected int layoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {
        PushManager.getInstance().turnOnPush(this);


        if (Build.VERSION.SDK_INT >= 23) {
            initGTPermission();
        }

        initActivity();
        checkVersionUpdate();

        mHomeFragment = new HomeFragment();
        mMoneyFragment = new MoneyFragment();

        mFragments = new BaseFragment[]{mHomeFragment, mMoneyFragment};

        setDefaultFragment();

    }

    private void initURL() {
        HttpUtils.getRequest(Constans.URl, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                TsUtils.showToast("服务器开小差了...");
                showDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                URLBean urlBean = JSON.parseObject(response, URLBean.class);
//                HttpManager.init(urlBean.getPro().getApiurl());
            }
        });
    }

    private void showDialog() {

        new AlertDialog.Builder(this)
                .setTitle("网络错误")
                .setMessage("服务器开小差了...")
                .setPositiveButton("点击重试",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                initURL();
                                dialog.dismiss();
                            }
                        })
                .
                        setNegativeButton("点击退出",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        IApplication.getInstance().destory();
                                        finish();
                                        dialog.dismiss();
                                    }
                                }
                        )
                .show();
    }


    /**
     * 设置默认的fragment
     */
    private void setDefaultFragment() {

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (mHomeFragment == null) {
            mHomeFragment = new HomeFragment();
        }
        transaction.replace(R.id.fl_frameLayout, mHomeFragment);
        transaction.commit();
    }

    @Override
    protected void initView() {
        mHome.setSelected(true);
    }

    @Override
    protected void showView() {
    }

    @OnClick({R.id.btn_home, R.id.btn_money})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_home:
                mMoney.setSelected(false);
                mHome.setSelected(true);
                setFragment(0);
                break;
            case R.id.btn_money:

                if (AppHelp.getInstance().getIsFinancial() == 0) {
                    TsUtils.showToast("请先申请多方金福");
                    return;
                }
                mHome.setSelected(false);
                mMoney.setSelected(true);
                setFragment(1);
                break;
            default:
                break;
        }
    }

    /**
     * 显示Fragment
     *
     * @param index
     */
    private void setFragment(int index) {

        FragmentManager fragmentManager = getSupportFragmentManager();

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        //                使用当前fragment属性代替framelayout
        fragmentTransaction.replace(R.id.fl_frameLayout, mFragments[index]);

        fragmentTransaction.commit();

    }

    private void initGTPermission() {

        new SimpleRuntimePermission(this)
                .request(
                        new SimpleRuntimePermission.PermissionListener() {
                            @Override
                            public void onAllPermissionGranted() {
                                initPush();
                            }

                            @Override
                            public void onPermissionRefuse(PermissionRefuseResultHelper resultHelper) {
                                showToast("没有获取到权限，有订单时将无法提醒");
                            }
                        }
                        , new ShowRequestPermissionRationaleListener() {
                            @Override
                            public void onShowRequestPermissionRationale(final ShowRequestPermissionRationaleControler controler, String[] permissions) {
                                new AlertDialog.Builder(MainActivity.this)
                                        .setTitle("权限请求")
                                        .setMessage("获取权限，当有新订单时做提醒")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                controler.doContinue();
                                            }
                                        })
                                        .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                controler.doCancel();
                                            }
                                        })
                                        .create()
                                        .show();
                            }

                            @Override
                            public void onRequestPermissionRationaleRefuse(String[] permissions) {
                                Toast.makeText(MainActivity.this, "Fail, user refused request permission tip", Toast.LENGTH_SHORT).show();
                            }
                        }
                        , android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE
                );
    }

    private void initPush() {
        PushManager.getInstance().initialize(MainActivity.this.getApplicationContext(), PushService.class);
    }


    /**
     * 自动更新，判断当前版本号与服务器版本号是否相同
     */
    private void checkVersionUpdate() {

        HttpManager
                .instance()
                .updateVersion(new ReqVersion())
                .subscribe(new ErrorHandleSubscriber<VersionUpdate>() {
                               @Override
                               public void onNext(@NonNull VersionUpdate data) {
                                   //                       服务器版本
                                   int versionCode = data.getVersionCode();
                                   updateMessage = data.getUpdateMessage();
                                   apkUrl = data.getUrl();
                                   //                   当前应用版本
                                   int currentCode = AppUtils.getVersionCode(MainActivity.this);
                                   //        如果当前版本低于最新版本，更新数据
                                   if (versionCode > currentCode) {
                                       initPermission();
                                   }

                               }
                           }
                );

    }


    private void showDialog(String updateMessage, final String apkUrl) {

        if (AppUtils.isContextValid(this)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.android_auto_update_dialog_title);
            builder.setMessage(Html.fromHtml(updateMessage))
                    .setPositiveButton(R.string.android_auto_update_dialog_btn_download, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            goToDownload(apkUrl);
                        }
                    })
                    .setNegativeButton(R.string.android_auto_update_dialog_btn_cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                        }
                    });

            AlertDialog dialog = builder.create();
            //点击对话框外面,对话框不消失
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
    }

    /**
     * 6.0权限获取
     */
    private void initPermission() {

        new SimpleRuntimePermission(this)
                .request(
                        new SimpleRuntimePermission.PermissionListener() {
                            @Override
                            public void onAllPermissionGranted() {
                                showDialog(updateMessage, apkUrl);
                            }

                            @Override
                            public void onPermissionRefuse(PermissionRefuseResultHelper resultHelper) {
                                showToast("请求权限失败");
                            }
                        }
                        , new ShowRequestPermissionRationaleListener() {
                            @Override
                            public void onShowRequestPermissionRationale(final ShowRequestPermissionRationaleControler controler, String[] permissions) {
                                new AlertDialog.Builder(MainActivity.this)
                                        .setTitle("权限请求")
                                        .setMessage("请选择OK，加载新版本")
                                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                controler.doContinue();
                                            }
                                        })
                                        .setNegativeButton("Refuse", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                controler.doCancel();
                                            }
                                        })
                                        .create()
                                        .show();
                            }

                            @Override
                            public void onRequestPermissionRationaleRefuse(String[] permissions) {
                                Toast.makeText(MainActivity.this, "Fail, user refused request permission tip", Toast.LENGTH_SHORT).show();
                            }
                        }
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE
                );
    }


    //    向用户解释为什么需要这个权限的方法上。
    private void goToDownload(String downloadUrl) {
        Intent intent = new Intent(this, DownloadService.class);
        intent.putExtra(Constans.APK_DOWNLOAD_URL, downloadUrl);
        startService(intent);
    }

    private void initActivity() {
        List<BaseActivity> activities = IApplication.getInstance().getActivities();
        for (int i = 0; i < activities.size(); i++) {
            BaseActivity activity = activities.get(i);
            switch (activity.getLocalClassName()) {
                case "activity.MainActivity":
                    break;
                default:
                    activity.finish();
                    break;
            }
        }
    }


}
